﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the Microsoft Public License (Ms-PL).
// See accompanying file License.txt or copy at http://mews.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Mews.Net.Nntp.Cache
{
    using System;
    using System.Data.SqlServerCe;

    /// <summary>Simplifies transaction handling.</summary>
    internal struct Transaction : IDisposable
    {
        private readonly SqlCeCommand[] commands;
        private readonly SqlCeTransaction transaction;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="IDisposable.Dispose"/>.</summary>
        public void Dispose()
        {
            this.transaction.Dispose();

            foreach (var command in this.commands)
            {
                command.Transaction = null;
            }
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>Initializes a new instance of the <see cref="Transaction"/> struct.</summary>
        /// <param name="commands">The <see cref="SqlCeCommand"/> objects that are participating in the transaction.
        /// </param>
        internal Transaction(params SqlCeCommand[] commands)
        {
            this.commands = commands;
            this.transaction = commands[0].Connection.BeginTransaction();

            foreach (var command in this.commands)
            {
                command.Transaction = this.transaction;
            }
        }

        internal void Commit()
        {
            this.transaction.Commit();
        }
    }
}
